//
//  HMPictureSelectorController.swift
//  WeiboTT
//
//  Created by 王嘉涛 on 2016/11/22.
//  Copyright © 2016年 王嘉涛. All rights reserved.
//

import UIKit

let colCount : CGFloat = 3
let selectorMargin : CGFloat = 4
let selectorCellWidth = (ScreenWidth - (colCount + 1) * selectorMargin) / colCount
// 最大数量
private let maxCount = 9

private let reuseIdentifier = "Cell"

class HMPictureSelectorController: UICollectionViewController {

    // 定义图片数组,装用户选择的图片
    lazy var selectedImages : [UIImage] = [UIImage]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView!.register(PictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }
    
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let delta = self.selectedImages.count == maxCount ? 0 : 1
        return self.selectedImages.count + delta
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PictureSelectorCell
        
        // 设置代理
        cell.delegate = self
        // 给cell设置数据,判断如果是加载的最后一条数据就特殊处理
        if indexPath.item == self.selectedImages.count {
            // 给最后一个cell的数据赋值
            cell.image = nil
        } else {
            cell.image = self.selectedImages[indexPath.item]
        }
        return cell
    }
}

// MARK: 遵守cell的协议,实现协议方法
extension HMPictureSelectorController:PictureSelectorCellDelegate {
    func userWillChosePic(cell: PictureSelectorCell?) {
        //modal 图片选择控制器
        let picker = UIImagePickerController()
        //是否允许编辑
        //picker.allowsEditing = true
        //设置picker代理
        picker.delegate = self
        //modal
        self.present(picker, animated: true, completion: nil)
        
    }
    
    func userWillRemovePic(cell: PictureSelectorCell) {
        print(#function)
        //0.根据被点击的cell 通过collectionView 获取对应的indexPath
        guard let indexPath = collectionView?.indexPath(for: cell) else {
            return
        }
        //1.在数组删除 '对应' 的图片
        self.selectedImages.remove(at: indexPath.item)
        //2.刷新数据
        self.collectionView?.reloadData()
        //没有图片的时候就隐藏图片视图
        self.view.isHidden = self.selectedImages.count == 0
    }
}

// 遵守图片选择器的协议
extension HMPictureSelectorController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    // 实现协议方法,一旦实现该方法,程序员需要手动dismiss
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        // 获取选择图片
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        // 将图片添加到数组中
        self.selectedImages.append(image.scaleImage(width: ScreenWidth))
        //dismiss 控制器
        dismiss(animated: true, completion: {
            //刷新collectionView
            //self.collectionView?.reloadData()
        })
        self.collectionView?.reloadData()
    }
    
}

// 定义协议
@objc protocol PictureSelectorCellDelegate:NSObjectProtocol {
    // 可选的协议方法
    //添加图片
    @objc optional func userWillChosePic(cell: PictureSelectorCell?)
    //删除图片
    @objc optional func userWillRemovePic(cell: PictureSelectorCell)
}

// 自定义cell
class PictureSelectorCell: UICollectionViewCell {
    // cell的事件抛出,不建议使用闭包,使用代理
    // 使用weak修饰
    weak var delegate: PictureSelectorCellDelegate?
    
    var image : UIImage? {
        didSet {
            // 设置添加按钮的image
            addBtn.setImage(image, for: .normal)
            removeBtn.isHidden = image == nil
        }
    }
    @objc private func addBtnDidClick() {
        
        //跳转到选择图片的控制器 cell中不能够完成跳转 应该将事件传递给 控制器
        //调用代理方法
        if image != nil {
            return
        }
        delegate?.userWillChosePic?(cell: self)
    }
    
    @objc private func removeBtnDidClick() {
        //removeClosure?()
        delegate?.userWillRemovePic?(cell: self)
    }
    
    
    //重写init方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: 设置UI界面
    private func setupUI() {
        self.contentView.addSubview(addBtn)
        self.contentView.addSubview(removeBtn)
        
        //设置约束
        addBtn.snp.makeConstraints { (make) in
            make.edges.equalTo(self)
        }
        
        removeBtn.snp.makeConstraints { (make) in
            make.right.top.equalTo(self.contentView)
        }
        
        //监听按钮点击事件
        addBtn.addTarget(self, action: #selector(addBtnDidClick), for: .touchUpInside)
        removeBtn.addTarget(self, action: #selector(removeBtnDidClick), for: .touchUpInside)
        
    }
    
    //懒加载视图
    lazy var addBtn: UIButton = {
        let btn = UIButton()
        //设置图片
        btn.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add"), for: .normal)
        btn.imageView?.contentMode = .scaleAspectFill
        return btn
    }()
    
    lazy var removeBtn: UIButton = {
        let btn = UIButton()
        //设置图片
        btn.setImage(#imageLiteral(resourceName: "compose_photo_close"), for: .normal)
        return btn
    }()

}
